import React, { useState, useEffect } from 'react';
import { Card, Tabs, Form, Input, Button, Select, Space, Tag, message, Upload, Table } from 'antd';
import { UploadOutlined, SyncOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { fetchModels } from '../models/modelSlice';
import { predictComment, batchPredictComments } from '@/api/commentApi';
import { RootState, AppDispatch } from '@/store';
import { PredictionResult } from '@/types/comment';

const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

const PredictionPage: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const { models } = useSelector((state: RootState) => state.models);
  const [form] = Form.useForm();
  const [batchForm] = Form.useForm();
  const [predictionResult, setPredictionResult] = useState<PredictionResult | null>(null);
  const [batchResults, setBatchResults] = useState<PredictionResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [batchLoading, setBatchLoading] = useState(false);
  const [defaultModel, setDefaultModel] = useState<string>('');

  // 获取模型列表
  useEffect(() => {
  dispatch(fetchModels());
  }, [dispatch]);

  // 设置默认模型
  useEffect(() => {
    if (models.length > 0) {
      const defModel = models.find(m => m.isDefault) || models[0];
      setDefaultModel(defModel.id);
      form.setFieldsValue({ modelId: defModel.id });
      batchForm.setFieldsValue({ modelId: defModel.id });
    }
  }, [models, form, batchForm]);

  // 处理单条评论预测
  const handlePredict = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const result = await predictComment(values.comment, values.modelId);
      setPredictionResult(result);
      message.success('预测完成');
    } catch (error) {
      console.error('Prediction error:', error);
      message.error('预测失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理批量预测
  const handleBatchPredict = async () => {
    try {
      const values = await batchForm.validateFields();
      setBatchLoading(true);
      // 这里只是模拟批量预测，实际应处理上传的文件
      const mockComments = values.comments.split('\n').filter(Boolean);
      if (mockComments.length === 0) {
        message.warning('请输入至少一条评论');
        return;
      }
      
      // 模拟API调用
      const results = await batchPredictComments({
        comments: mockComments,
        modelId: values.modelId
      });
      
      setBatchResults(results);
      message.success(`批量预测完成，共处理 ${results.length} 条评论`);
    } catch (error) {
      console.error('Batch prediction error:', error);
      message.error('批量预测失败，请重试');
    } finally {
      setBatchLoading(false);
    }
  };

  // 表格列定义（批量预测结果）
  const batchResultColumns = [
    {
      title: '评论内容',
      dataIndex: 'comment',
      key: 'comment',
      ellipsis: true,
    },
    {
      title: '预测标签',
      key: 'tags',
      render: (_: any, record: any) => (
        <Space size="small">
          {record.tags.map((tag: any) => (
            <Tag key={tag.id} color={tag.color}>{tag.name}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '置信度',
      dataIndex: 'confidence',
      key: 'confidence',
      render: (confidence: number) => `${(confidence * 100).toFixed(1)}%`,
    },
  ];

  return (
    <Card title="评论标签预测">
      <Tabs defaultActiveKey="single" style={{ marginTop: 16 }}>
        {/* 单条评论预测 */}
        <TabPane tab="单条评论预测" key="single">
          <Form form={form} layout="vertical" initialValues={{ modelId: defaultModel }}>
            <Form.Item
              name="comment"
              label="评论内容"
              rules={[{ required: true, message: '请输入评论内容' }]}
            >
              <TextArea rows={6} placeholder="请输入要预测的评论内容..." />
            </Form.Item>

            <Form.Item
              name="modelId"
              label="选择模型"
              rules={[{ required: true, message: '请选择预测模型' }]}
            >
              <Select placeholder="请选择模型">
                {models.map(model => (
                  <Option key={model.id} value={model.id}>
                    {model.name} (准确率: {model.accuracy * 100}%)
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                onClick={handlePredict} 
                loading={loading}
                icon={loading ? <SyncOutlined spin /> : null}
              >
                开始预测
              </Button>
            </Form.Item>
          </Form>

          {/* 预测结果展示 */}
          {predictionResult && (
            <Card title="预测结果" style={{ marginTop: 20 }}>
              <div style={{ marginBottom: 16 }}>
                <strong>评论内容：</strong>
                <p>{form.getFieldValue('comment')}</p>
              </div>
              
              <div style={{ marginBottom: 16 }}>
                <strong>预测标签：</strong>
                <Space size="small" style={{ marginTop: 8 }}>
                  {predictionResult.tags.map(tag => (
                    <Tag key={tag.tagId}>{tag.tagName}{tag.confidence * 100}%</Tag>
                  ))}
                </Space>
              </div>
              
              <div>
                <strong>模型信息：</strong>
                <p>模型名称：{models.find(m => m.id === predictionResult.modelId)?.name}</p>
                <p>预测时间：{new Date().toLocaleString()}</p>
              </div>
            </Card>
          )}
        </TabPane>

        {/* 批量评论预测 */}
        <TabPane tab="批量评论预测" key="batch">
          <Form form={batchForm} layout="vertical" initialValues={{ modelId: defaultModel }}>
            <Form.Item
              name="comments"
              label="批量评论"
              rules={[{ required: false, message: '请输入批量评论内容' }]}
              tooltip="每行输入一条评论内容，或通过文件上传"
            >
              <TextArea rows={6} placeholder="请输入批量评论内容，每行一条..." />
            </Form.Item>

            <Form.Item label="或上传文件">
              <Upload
                name="file"
                action="/api/upload"
                accept=".txt,.csv"
                showUploadList
                beforeUpload={(file) => {
                  // 这里只是前端预览，实际上传处理需要后端支持
                  message.info(`文件 ${file.name} 准备上传，实际项目中需要后端接口支持`);
                  return false; // 阻止自动上传
                }}
              >
                <Button icon={<UploadOutlined />}>选择文件</Button>
              </Upload>
              <p style={{ marginTop: 8, color: '#666', fontSize: 12 }}>
                支持格式：.txt, .csv，每行一条评论
              </p>
            </Form.Item>

            <Form.Item
              name="modelId"
              label="选择模型"
              rules={[{ required: true, message: '请选择预测模型' }]}
            >
              <Select placeholder="请选择模型">
                {models.map(model => (
                  <Option key={model.id} value={model.id}>
                    {model.name} (准确率: {model.accuracy * 100}%)
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                onClick={handleBatchPredict} 
                loading={batchLoading}
                icon={batchLoading ? <SyncOutlined spin /> : null}
              >
                开始批量预测
              </Button>
            </Form.Item>
          </Form>

          {/* 批量预测结果展示 */}
          {batchResults.length > 0 && (
            <Card title={`批量预测结果 (共${batchResults.length}条)`} style={{ marginTop: 20 }}>
              <Table
                columns={batchResultColumns}
                dataSource={batchResults}
                rowKey={(record, index) => `batch-${index}`}
                pagination={{ pageSize: 5 }}
              />
            </Card>
          )}
        </TabPane>
      </Tabs>
    </Card>
  );
};

export default PredictionPage;
    